package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"house/models"
	"math"
)

type HouseController struct {
	beego.Controller
}
type Msg struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}
type MsgPage struct {
	Code    int         `json:"code"`
	Msg     string      `json:"msg"`
	Data    interface{} `json:"data"`
	Size    int         `json:"size"`
	Page    int         `json:"page"`
	Count   int64       `json:"count"`
	Sumpage int         `json:"sumpage"`
}

func (c *HouseController) Add() {
	address := c.GetString("address")

	name := c.GetString("name")
	men, _ := c.GetInt("men")
	house_id, _ := c.GetInt("house_id")
	status := c.GetString("status")
	standard := c.GetString("standard")
	area, _ := c.GetFloat("area")
	rent, _ := c.GetInt("rent")
	var house = models.House{
		Address:  address,
		Name:     name,
		Men:      men,
		HouseID:  house_id,
		Status:   status,
		Standard: standard,
		Area:     area,
		Rent:     rent,
	}
	err := models.DB.Create(&house).Error
	if err != nil {
		c.Data["json"] = Msg{
			Code: 0,
			Msg:  "添加失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Msg{
			Code: 200,
			Msg:  "添加成功",
			Data: house,
		}
		c.ServeJSON()
	}
}

func (c *HouseController) Page() {
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	var count int64
	models.DB.Model(&models.House{}).Count(&count)
	sumpage := int(math.Ceil(float64(count) / float64(size)))
	if page > sumpage {
		page = sumpage
	}
	offset := (page - 1) * size
	var allhouse []models.House
	err := models.DB.Offset(offset).Limit(size).Find(&allhouse).Error
	if err != nil {
		c.Data["json"] = Msg{
			Code: 0,
			Msg:  "分页查询失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = MsgPage{
			Code:    200,
			Msg:     "分页查村成功",
			Data:    allhouse,
			Size:    size,
			Page:    page,
			Count:   count,
			Sumpage: sumpage,
		}
		c.ServeJSON()
	}
}
func (c *HouseController) Del() {
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.House{}, id).Error
	if err != nil {
		c.Data["json"] = Msg{
			Code: 0,
			Msg:  "删除失败",
			Data: nil,
		}
		c.ServeJSON()
	} else {
		c.Data["json"] = Msg{
			Code: 200,
			Msg:  "删除成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
